package com.jourwon.spring.boot.handler.impl;

import com.jourwon.spring.boot.handler.FruitHandler;
import com.jourwon.spring.boot.handler.HandlerFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 水果处理器工厂
 *
 * @author JourWon
 * @date 2022/3/24
 */
@Slf4j
@Component
public class FruitHandlerFactoryImpl implements HandlerFactory<FruitHandler> {

    @Resource
    private List<FruitHandler> fruitHandlerList;

    private Map<String, FruitHandler> fruitHandlerMap = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() {
        fruitHandlerMap = fruitHandlerList.stream().collect(Collectors.toMap(FruitHandler::getType, Function.identity()));
    }

    @Override
    public FruitHandler getHandler(String type) {
        if (CollectionUtils.isEmpty(fruitHandlerMap)) {
            log.warn("水果处理器列表为空");
            return null;
        }

        return fruitHandlerMap.getOrDefault(type, null);
    }

}
